//var root = "/tms/";
var root = "http://180.76.51.106:8080/tms/";
// 引用axios
// var axios = require('axios') // commonjs格式
import axios from 'axios' // ES6写法
import qs from 'qs'
import { MessageBox } from 'mint-ui';

import { Indicator } from 'mint-ui';
/**
说明：
import list from './list';//ES6格式
//等价于
var list = require('./list'); //commonjs格式:经典的commonjs同步语法
**/

function BackTop(domE, distance) {
    var currentScroll = document.documentElement.scrollTop || document.body.scrollTop;
    if (currentScroll > 0) {
        window.requestAnimationFrame(BackTop);
        window.scrollTo(0, currentScroll - (currentScroll / 5));
    }
};
// 自定义判断元素类型JS
function toType(obj) {
    return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase()
}
// 参数过滤函数
function filterNull(o) {
    for (var key in o) {
        if (o[key] === null) {
            delete o[key]
        }
        if (toType(o[key]) === 'string') {
            o[key] = o[key].trim()
        } else if (toType(o[key]) === 'object') {
            o[key] = filterNull(o[key])
        } else if (toType(o[key]) === 'array') {
            o[key] = filterNull(o[key])
        }
    }
    return o
}
/*
  接口处理函数
  这个函数每个项目都是不一样的，我现在调整的是适用于
  https://cnodejs.org/api/v1 的接口，如果是其他接口
  需要根据接口的参数进行调整。参考说明文档地址：
  https://cnodejs.org/topic/5378720ed6e2d16149fa16bd
  主要是，不同的接口的成功标识和失败提示是不一致的。
  另外，不同的项目的处理方法也是不一致的，这里出错就是简单的alert
*/

function apiAxios(method, url, params, success, failure) {
    if (params) {
        params = filterNull(params)
    }
    let config = {
        method: method,
        url: url,
        // data: method === 'POST' || method === 'PUT'  ? qs.stringify(params) : null,
        params: method === 'GET' || method === 'DELETE' ? params : params,
        baseURL: root,
    }
    Indicator.open({
        text: '加载中...',
        spinnerType: 'fading-circle'
    });
    axios(config)
        .then(function(res) {
            Indicator.close();
            if (res.data.success === true) {
                if (success) {
                    success(res.data)
                }
            } else {
                if (failure) {
                    failure(res.data)
                } else {
                    MessageBox('提示', res.data.msg);
                }
            }
        })
        .catch(function(err) {
            Indicator.close();
            let res = err.response
            if (err) {
                if (res) {
                    window.alert('api error, HTTP CODE: ' + res.status)
                }
            }
        })
}


function getImage(success, failure) { // 拍照
    if (!window.plus) {
        MessageBox('提示', '当前设备不支持拍照！');
        return false;
    }
    console.log('开始拍照：');
    var cmr = plus.camera.getCamera();
    cmr.captureImage(function(p) {
        console.log('成功:' + p);
        plus.io.resolveLocalFileSystemURL(p, function(entry) {
            success(p, entry.toLocalURL());
            // entry.FileEntry((file)=>{
            //     console.log('typoffile'+typeof(file));
            //     success(p,entry.toLocalURL());
            // })

        }, function(e) {
            failure(entry);
            console.log('读取拍照文件错误：' + e.message);
        });
    }, function(e) {
        console.log('失败：' + e.message);
    }, { filename: '_doc/camera/', index: 1 });
}

function createUpload(url, params, success) { //上传图片  

    var task = plus.uploader.createUpload("http://180.76.51.106:8080/tms" + url, { method: "POST", blocksize: 204800, priority: 100 },
        function(t, status) {
            // 上传完成  
            if (status == 200) {
                console.log('提交成功')
                success(t);
            } else {
                console.log("Upload failed: " + status);
            }
        }
    );
    task.addFile(params.file, { key: "file" });
    task.addData("dispatch_no", params.dispatch_no);
    task.addData("source_unique_no", params.source_unique_no);
    //task.addEventListener( "statechanged", onStateChanged, false );  
    task.start();
}

function tell(number) { //打电话
    window.location.href = "tel:" + number;
}

function formatDate(now) {
    var year = now.getFullYear();
    var month = now.getMonth() + 1;
    var date = now.getDate();
    var hour = now.getHours();
    var minute = now.getMinutes();
    var second = now.getSeconds();
    return year + "-" + month + "-" + date
}

function formatTime(now) {
    var hour = now.getHours();
    var minute = now.getMinutes();
    if(hour<10){
        hour='0'+hour
    }
    if(minute<10){
        minute='0'+minute
    }
    var second = now.getSeconds();
    return hour + ":" + minute;
}

// 返回在vue模板中的调用接口

export default {
    get: function(url, params, success, failure) {
        return apiAxios('GET', url, params, success, failure)
    },
    post: function(url, params, success, failure, img) {
        return apiAxios('POST', url, params, success, failure, img)
    },
    put: function(url, params, success, failure) {
        return apiAxios('PUT', url, params, success, failure)
    },
    delete: function(url, params, success, failure) {
        return apiAxios('DELETE', url, params, success, failure)
    },
    tell: tell,
    getImage: getImage,
    formatData: formatDate,
    formatTime: formatTime,
    BackTop: BackTop,
    createUpload: createUpload,
}